package restlike.demo.royalbankofshoreditch

import java.util.Random

import im.mange.shoreditch.api._
import im.mange.shoreditch.api.liftweb.ServiceHelper
import ServiceHelper._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import im.mange.shoreditch.api.liftweb.ServiceHelper
import restlike.demo.shoreditchairways.IdFactory


//TODO: pullout/rename etc
object Generator {
  private val random = new Random()
  
  def string(characters: String, length: Int) = {
    val result = new Array[Char](length)
    var i = 0
    
    while (i < length) {
      result(i) = characters.charAt(random.nextInt(characters.length()))
      i = i + 1
    }

    new String(result)
  }
}

//http://localhost:4253/booking/metadata
object Booking extends ServiceHelper(base = "booking", version = "10001")(
  "create/trade/" action CreateTrade,
  "trade/booked/@id" check TradeBooked
)

case class TradeBooked(id: String) extends Check {
  override def run =
    if (DemoState.trades.exists(b => b.ref == id)) success
    else failure(List(s"Trade $id has not been booked"))
}

case object CreateTrade extends Action {
  override val parameters = Parameters(List(In("notional", None, Nil), In("currency", None, Nil)), Some(Out("id")))

  override def run(in: List[In]) = {
    //TODO: use a future to sleep a bit
    val trade = TradeRef("BOS-" + IdFactory.mumeric(5))

    Future {
      Thread.sleep(10000)
      DemoState.trades = trade :: DemoState.trades

      Thread.sleep(10000)
      trade.priced = true

      Thread.sleep(10000)
      trade.accepted = true

      Thread.sleep(10000)
      trade.cleared = true
    }

    success(Some(trade.ref))
  }
}
